/**
 * hooks 提取公共逻辑模块
 */

/**
 * 自定义的 useState 钩子，用于创建和管理响应式状态
 */
import { DeepReadonly, UnwrapNestedRefs, UnwrapRef } from 'vue';
type StateType<S> = S | (() => S) | Ref<S> | (() => Ref<S>);
export const useState = <S extends Record<string, any>>(
    init: StateType<S> | Number | string | boolean
): [
    DeepReadonly<UnwrapNestedRefs<[S] extends [Ref<any>] ? S : Ref<UnwrapRef<S>>>>,
    (patch: Record<string, any> | any, cover?: boolean) => void
] => {
    const getInitState = () => unref(init);
    const state = ref<S>(getInitState() as S);
    const setState = (patch: any, cover = false) => {
        const newState = unref(patch);
        if (cover) state.value = newState;
        else
            state.value =
                newState != null || undefined
                    ? typeof newState == 'object'
                        ? _.merge(state.value, newState)
                        : (state.value = newState)
                    : state.value;
    };
    // @ts-ignore
    return [readonly(state), setState];
};
